#!/usr/bin/env python

# (c) 2007-2011 Helsinki University of Technology and University of Helsinki
# Licensed under the MIT license; see LICENSE.txt for more information.

from harava.map import Mapper
from harava.rdf import *


KWLOOKUPSCHEMES = {
  'fi': ('ts.tero',),
  'sv': ('ts.tero-sv',),
  'en': ('ts.tero-en',),
  None: ('ts.tero',),
}


class ToSuEventMapper (Mapper):
  def __init__(self, session):
    Mapper.__init__(self, session)
    

  def process(self, doc):
    lookup = self._session.getLookupService()

    for kw in list(doc.getMetadata(TOSU.keyword)):
      # Process the TOSU.keyword values, trying to find matches in TERO
      # If matches are found, move the matched value to DCTERMS.subject
      if kw.language in KWLOOKUPSCHEMES:
        schemes = KWLOOKUPSCHEMES[kw.language]
      else: # unknown/nonexistent language, use default
        schemes = KWLOOKUPSCHEMES[None]

      for scheme in schemes:
        uris = lookup.lookup(doc, scheme, unicode(kw), language=kw.language, warn=False)
        if uris:
          doc.log('NOTE', 'map', 'Keyword lookup successful using scheme %s' % scheme, kw)
          doc.clearMetadata(TOSU.keyword, kw)
          for uri in uris:
            doc.setMetadata(DCTERMS.subject, uri)
          break
  
    
    # remove non-TERO subjects
    clearlist = []
    for subj in doc.getMetadata(DCTERMS.subject):
      if not subj.startswith(TERO):
        clearlist.append(subj)
    for subj in clearlist:
      doc.clearMetadata(DC.subject, subj)
    

    doc.setCompleted('map')
    self._session.schedule(doc)
    return True

  def finish(self):
    pass
